package http

import (
	"github.com/golang-jwt/jwt/v5"
	"github.com/xiyoufang/cloud-syncer/internal/env"
	"net/http"
	"strings"
	"time"
)

// CORS 中间件函数, 用于支持跨域
func corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Headers", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		if r.Method == http.MethodOptions {
			return
		}
		next.ServeHTTP(w, r)
	})
}

// 权限处理中间件
func jwtMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if strings.HasPrefix(r.URL.Path, "/api/login") { // 排除 /api/login 路径
			next.ServeHTTP(w, r)
			return
		}
		tokenString := r.Header.Get("Authorization")
		if tokenString == "" {
			http.Error(w, "Missing authorization token", http.StatusUnauthorized)
			return
		}
		tokenString = strings.TrimPrefix(tokenString, "Bearer ")
		_, b := env.Cache().Get(tokenString) // 判断Token是否存在
		if !b {
			http.Error(w, "Session is expired", http.StatusUnauthorized)
			return
		}
		claims := &jwt.RegisteredClaims{}
		token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
			return []byte(env.Config().Http.SecretKey), nil
		})
		if err != nil || !token.Valid {
			http.Error(w, "Invalid token", http.StatusUnauthorized)
			return
		}
		env.Cache().Refresh(tokenString, time.Duration(env.Config().Http.SessionTimeout)*time.Second)
		next.ServeHTTP(w, r)
	})
}
